﻿using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Framework.Serialization;
using IQIGame.Onigao.GamePlay;
using LFloatMath.Math;


namespace IQIGame.Onigao.Logic
{
    public class ChargeComponent : TComponent
    {
        private Unit unit;
        public ChargeItem charge;
        public bool ready => this.charge != null && (this.charge.chargeStartRound + this.charge.chargeDuration) <= this.unit.battle.playCtrl.RoundNum;

        protected override void OnDispose()
        {
        }

        public override void OnCreate(TEntity entity)
        {
            this.unit = entity as Unit;
        }

        public void StartCharge(int duration, int skillID, SelectParam select, SkillEffectiveData rData, string chargePrefab)
        {
            var rCustomPropertyComp = this.unit.GetComponent<CustomPropertyComponent>(ETComponentType.CustomPropertyComponent);
            if (!rCustomPropertyComp.GetProperty<bool>(ECustomProperty.Charge))
            {
                var rCharge = ClassPool.Get<ChargeItem>();
                rCharge.chargeDuration = duration;
                rCharge.castSkill = skillID;
                rCharge.chargeStartRound = this.unit.battle.playCtrl.RoundNum;
                rCharge.pos = select.unit?.pos ?? select.pos;
                rCharge.aspect = select.aspect;
                this.charge = rCharge;

                var rResultCtrl = this.unit.battle.playCtrl.resultCtrl;
                rResultCtrl.Add(BattleUpdateFactory.CreateCharge(this.unit, duration, skillID, select, rData, chargePrefab));
                rCustomPropertyComp.SetProperty(ECustomProperty.Charge, true, ETAnyType.Bool);
            }
        }

        /// <summary>
        /// 蓄力中是否蓄力完成
        /// </summary>
        /// <param name="rCurTurn"></param>
        /// <returns></returns>
        public bool ChargeReady(BattleTurnQueueController.TurnPart rCurTurn)
        {
            if (this.ready)
            {
                var rCharge = this.charge;
                var nChargeSkill = rCharge.castSkill;
                var rSkillComp = this.unit.GetComponent<SkillComponent>(ETComponentType.SkillComponent);
                if (rSkillComp.skillDict.TryGetValue(nChargeSkill, out var rSkill))
                {
                    rCurTurn.curSkill = rSkill;
                    rCurTurn.Input(rCharge.pos, rCharge.aspect);
                }
                this.ChargeStop();
                
                return true;
            }
            return false;
        }

        public void ChargeStop()
        {
            this.charge = null;

            var rCustomPropertyComp = this.unit.GetComponent<CustomPropertyComponent>(ETComponentType.CustomPropertyComponent);
            rCustomPropertyComp.SetProperty(ECustomProperty.Charge, false, ETAnyType.Bool);
            
            var rResultCtrl = this.unit.battle.playCtrl.resultCtrl;
            rResultCtrl.Add(BattleUpdateFactory.CreateChargeStop(this.unit));
        }
    }
}